package com.framework.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.nio.ch.IOUtil;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/5/15 20:55
 * @since JDK 1.8
 */
@Component
@Slf4j
public class OSSClientUtil {

    @Value("${aliyun.oss.endPoint}")
    private String ossEndpoint;

    @Value("${aliyun.oss.endPoint.internal}")
    private String ossEndpointInternal;

    @Value("${aliyun.oss.accessKeyId}")
    private String ossAccessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String ossAccessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    private String filedir = "ttzdir/";

    private String openFiledir = "ttzdir-open/";

    private OSS ossClient;

    @PostConstruct
    public void init() {
         ossClient = new OSSClientBuilder().build(ossEndpoint, ossAccessKeyId, ossAccessKeySecret);
         createBucketName(bucketName);
    }

    @PreDestroy
    private void destory() {
        if(ossClient != null) {
            ossClient.shutdown();
            log.info("ossClient销毁成功");
        }
    }

    /** 
     * 创建存储空间 
     * @param ossClient      OSS连接 
     * @param bucketName 存储空间 
     * @return 
     * */
    private String createBucketName(String bucketName) {
        if (!ossClient.doesBucketExist(bucketName)) {
            log.info("[文件上传至OSS]-bucket不存在，创建一个新的-bucketName=[{}]", bucketName);
            Bucket bucket = ossClient.createBucket(bucketName);
            return bucket.getName();
        }
        return bucketName;
    }
    /**
     * 上传文件到OSS
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFileToOSS(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String fileName = UUID.randomUUID().toString() + substring;
        InputStream inputStream = null;
        inputStream = file.getInputStream();
        return this.uploadFile2OSS(inputStream, fileName);
    }

    /**
     * 上传文件到OSS
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadOpenFileToOSS(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String fileName = UUID.randomUUID().toString() + substring;
        InputStream inputStream = null;
        inputStream = file.getInputStream();
        return this.uploadOpenFile2OSS(inputStream, fileName);
    }

    /**
     * 上传图片至OSS
     * @return String 返回的唯一MD5数字签名
     */
    public String uploadObject2OSS(InputStream is, String fileName) {
        String resultStr = null;
        try {
            // 创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            // 上传的文件的长度
            metadata.setContentLength(is.available());
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            // 如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileName));
            // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            String filePath = filedir + fileName;
            metadata.setContentDisposition("filename/filesize=" + (filePath));
            // 上传文件 (上传文件流的形式)
            PutObjectResult putResult = ossClient.putObject(bucketName, filePath, is, metadata);
            // 解析结果
            // PutObjectResult putResult = ossClient.putObject(bucketName, filePath, is, metadata);
            resultStr = putResult.getETag();
            StringBuilder sb = new StringBuilder(ossEndpoint + "/" + filePath);// 构造一个StringBuilder对象
            sb.insert(7, bucketName + ".");// 在指定的位置插入指定的字符串
            resultStr = sb.toString();
            // 关闭OSSClient。
            //
        } catch (Exception e) {
            log.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        return resultStr;
    }

    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = null;
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            String filePath = filedir + fileName;
            // 上传文件
            ossClient.putObject(bucketName, filePath, instream, objectMetadata);
            //ret = ossEndpoint + "/" + filePath;
            //ret = getUrl(filePath);
            ret = fileName;
            // ret = putResult.getETag();
            // 关闭OSSClient。
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return ret;
    }

    public String uploadOpenFile2OSS(InputStream instream, String fileName) {
        String ret = null;
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            if(fileName.contains(".")) {
                objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            } else {
                objectMetadata.setContentType(getcontentType(fileName));
            }

            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            String filePath = openFiledir + fileName;
            // 上传文件
            ossClient.putObject(bucketName, filePath, instream, objectMetadata);
            ossClient.setObjectAcl(bucketName, filePath, CannedAccessControlList.PublicRead);
            StringBuilder sb = new StringBuilder(ossEndpoint + "/" + filePath);// 构造一个StringBuilder对象
            sb.insert(8, bucketName + ".");// 在指定的位置插入指定的字符串
            ret = sb.toString();
            //ret = getUrl(filePath);
            //ret = fileName;
            // ret = putResult.getETag();
            // 关闭OSSClient。
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return ret;
    }

    /**
     * 将byte数组上传至OSS
     * @param bcyte
     * @param fileName
     * @return
     */
    public String uploadByByteToOSS(byte[] bcyte, String fileName) {
        String resultStr = null;
        Long fileSize = (long) bcyte.length;
        // 创建上传Object的Metadata
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(fileSize);
        // 指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        // 指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        // 指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        // 如果没有扩展名则填默认值application/octet-stream
        metadata.setContentType(getContentType(fileName));
        // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        String filePath = filedir + fileName;
        // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
        ossClient.putObject(bucketName, filePath, new ByteArrayInputStream(bcyte),
                metadata);
        // -------------------
        StringBuilder sb = new StringBuilder(ossEndpoint + "/" + filePath);// 构造一个StringBuilder对象
        sb.insert(7, bucketName + ".");// 在指定的位置插入指定的字符串
        resultStr = sb.toString();
        // -------------------

        return resultStr;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     * @param fileName 文件名
     * @return 文件的contentType
     */
    private  String getContentType(String fileName) {
        log.info("getContentType:" + fileName);
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".pdf".equalsIgnoreCase(fileExtension)) {
            return "application/pdf";
        }
        // 默认返回类型
        return "image/jpeg";
    }

    /**
     * 获取文件上传时的contentType
     * @param filenameExtension
     * @return
     */
    private  String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
                || filenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得图片路径
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.filedir + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 获得url链接
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     * @Title: getInputStreamByFileUrl
     * @Description: 根据文件路径获取InputStream流
     * @param fileName
     * @return
     * @return: InputStream
     */
    public InputStream getInputStreamByFileUrl(String fileName) {
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, filedir + fileName);
        return ossObject.getObjectContent();
    }
}
